package com.nantong.admin.config;

import cn.dev33.satoken.interceptor.SaInterceptor;
import cn.dev33.satoken.router.SaRouter;
import cn.dev33.satoken.stp.StpUtil;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * Sa-Token 配置类
 *
 * @author nantong
 */
@Configuration
public class SaTokenConfig implements WebMvcConfigurer {

    /**
     * 注册Sa-Token拦截器，打开注解式鉴权功能
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 注册Sa-Token拦截器，校验规则为StpUtil.checkLogin()登录校验。
        registry.addInterceptor(new SaInterceptor(handle -> {
            // 登录校验 -- 所有路径都需要登录认证
            SaRouter.match("/**")
                    .notMatch(
                            // 排除预检请求OPTIONS
                            "OPTIONS", 
                            // 登录和登出接口
                            "/api/system/auth/login",
                            "/api/system/auth/logout",
                            // Swagger相关资源
                            "/v3/api-docs",
                            "/*/v3/api-docs",
                            "/swagger-ui/**",
                            "/swagger-ui.html",
                            "/webjars/**",
                            "/swagger-resources/**",
                            "/favicon.ico"
                    )
                    .check(r -> {
                        StpUtil.checkLogin();
                    });
        })).addPathPatterns("/**");
    }
}

